<script setup>
import { watch, computed } from 'vue'
import { User, Iphone, Postcard, Switch, PriceTag, Location, Tickets, OfficeBuilding } from "@element-plus/icons-vue";
// 姓名，电话，所属，线条标签，人员信息
import TextInputSwitch from '../Tool/TextInputSwitch.vue'
import NewPeople from "../Relation/NewPeople.vue"

const props = defineProps(['selectedPeople', 'groups', 'handleRaws', 'raws'])

// 是props.selectedPeople的复制品，但是修改要通过他，不影响父组件的数据
const peopleForm = ref({})
const isEdit = ref(false)
const peopleTabName = ref('new')

// 更新按钮
const update = () => {
  console.log(peopleForm.value)
  myPost("/relation/update", { userToken: window.User.token, relationJson: JSON.stringify(peopleForm.value) },
    (data) => {
      ElMessage({ message: '成功修改 ' + data + ' 条人员', type: 'success' })
      isEdit.value = false
      props.handleRaws(peopleForm.value)
    })
}
// 如果选中的是人员要转换一下数据，如info要JSON转换
const initPeopleForm = () => {
  peopleForm.value = JSON.parse(JSON.stringify(props.selectedPeople.raw))
  if (peopleForm.value.rInfo) peopleForm.value.rInfo = JSON.parse(peopleForm.value.rInfo)
  else peopleForm.value.rInfo = {}
  isEdit.value = false
}

// 当用户选中某节点时，将数据复制到本组件
watch(() => props.selectedPeople, (newValue) => {
  if (props.selectedPeople.id > 0) {
    initPeopleForm()
    peopleTabName.value = 'info'
  } else if (props.selectedPeople.id < 0) {
    peopleTabName.value = 'group'
  } else {
    peopleTabName.value = 'new'
  }
}, { immediate: true })

// rGroup 和 rFromId 的抉择
const rFrom = computed({
  get() {
    return peopleForm.value.rFromId ?? peopleForm.value.rGroup
  },
  set(value) {
    if (/^[0-9]*$/.test(value) && value != '') {
      delete peopleForm.value.rGroup
      peopleForm.value.rFromId = parseInt(value)
    } else {
      delete peopleForm.value.rFromId
      peopleForm.value.rGroup = value
    }
  }
})

// 添加框
const infoKey = ref('')
const infoValue = ref('')
const addInfo = () => {
  if (!handlInfo()) return;
  peopleForm.value.rInfo[infoKey.value] = infoValue.value.trim()
  infoValue.value = infoKey.value = ''
}
// 判断info的key&value是否正确
const handlInfo = () => {
  if (infoKey.value == '') {
    ElMessage.error("项名称不能为空")
    return false
  }
  if (parseInt(infoKey.value)) {
    ElMessage.error('项目名称不能以数字开头')
    return false
  }
  if (infoValue.value.trim() == '') {
    ElMessage.error("项内容不能为空")
    return false
  }
  return true
}

// 添加节点*****************************
const newPeopleForm = reactive({ rName: '', rNumber: '', rEdgeLabel: '' })

// 添加组员和后继人员
const newPeople = () => {
  if (!newPeopleForm.rName) {
    ElMessage.error('姓名不能为空')
    return;
  }
  if (props.selectedPeople.id > 0) newPeopleForm.rFromId = peopleForm.value.rId
  else newPeopleForm.rGroup = props.selectedPeople.label

  console.log(JSON.stringify(newPeopleForm))
  myPost("/relation/new", { userToken: window.User.token, relationJson: JSON.stringify(newPeopleForm) },
    (newPeopleId) => {
      ElMessage({ message: '添加成功，新人员ID为 ' + newPeopleId, type: 'success' })
      props.handleRaws({ ...newPeopleForm, rId: newPeopleId })
      // 表单初始化
      newPeopleForm.rName = newPeopleForm.rNumber = newPeopleForm.rEdgeLabel = ''
      delete newPeopleForm.rFromId, newPeopleForm.rGroup
    })
}

// 删除节点===========================
const delPeople = (r) => {
  myPost("/relation/delete", { userToken: window.User.token, rId: r.rId },
    (data) => {
      ElMessage({ message: '成功删除 ' + data + ' 条人员', type: 'success' })
      props.handleRaws(r)
    })
}
</script>

<template>
  <!-- 查看人员表单 -->
  <div class="model people">
    <!-- 人员信息展示 -->
    <div class="info" v-if="selectedPeople.id > 0">
      <div><el-avatar size="large" :src="' https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" />
      </div>
      <div>ID: {{ selectedPeople.raw.rId }}</div>
      <div>{{ selectedPeople.raw.rName }}</div>
      <div>{{ selectedPeople.from }}</div>
      <!-- <div>电话</div> -->
      <el-button type="primary" size="small" @click="delPeople(selectedPeople.raw)"
        style="margin-top: 10px">删除节点</el-button>
    </div>

    <!-- 对人员的操作 -->
    <div class="handl">
      <el-tabs v-model="peopleTabName">

        <!-- 添加人员标签页 -->
        <el-tab-pane label="添加人员" name="new">
          <NewPeople :groups="groups" :handleRaws="handleRaws" />
        </el-tab-pane>

        <!-- 人员信息标签页 -->
        <el-tab-pane label="人员信息" name="info" v-if="selectedPeople.id > 0">
          <div class="base-info">
            <div class="info-item">
              <span class="key">
                <el-icon>
                  <User />
                </el-icon> 姓名
              </span>
              <span class="value">
                <span v-if="!isEdit">{{ peopleForm.rName }}</span>
                <el-input v-if="isEdit" v-model.trim="peopleForm.rName" style="width: 200px" />
              </span>
            </div>
            <div class="info-item">
              <span class="key">
                <el-icon>
                  <Iphone />
                </el-icon> 电话
              </span>
              <span class="value">
                <span v-if="!isEdit">{{ peopleForm.rNumber }}</span>
                <el-input v-if="isEdit" v-model.trim="peopleForm.rNumber" style="width: 200px" />
              </span>
            </div>
            <div class="info-item">
              <span class="key">
                <el-icon>
                  <Switch />
                </el-icon> 所属
              </span>
              <span class="value">
                <!-- 要特殊处理 -->
                <span v-if="!isEdit">{{ rFrom }}</span>
                <el-input v-if="isEdit" v-model.trim="rFrom" style="width: 200px" />
              </span>
            </div>
            <div class="info-item">
              <span class="key">
                <el-icon>
                  <PriceTag />
                </el-icon> 关系
              </span>
              <span class="value">
                <span v-if="!isEdit">{{ peopleForm.rEdgeLabel }}</span>
                <el-input v-if="isEdit" v-model.trim="peopleForm.rEdgeLabel" style="width: 200px" />
              </span>
            </div>
          </div>

          <div class="other-info" v-if="isEdit || Object.keys(peopleForm.rInfo).length">
            <div style="margin-top:10px;margin-bottom:5px;">更多信息项</div>

            <div class="info-item" v-for="(value, key) of peopleForm.rInfo" :key="key">
              <span class="key"> {{ key }} </span>
              <span class="value">
                <TextInputSwitch :data="peopleForm" :index="'rInfo.' + key" />
              </span>
              <el-button v-if="isEdit" size="small" text @click="delete peopleForm.rInfo[key]">❌</el-button>
            </div>

            <div class="add-item" style="margin-top:5px">
              <span class="key">
                <span v-if="isEdit">
                  <el-input v-model.trim="infoKey" placeholder="项名称"
                    style="width: 80px;margin-right: 5px;margin-bottom:5px" />
                  <el-input v-model="infoValue" @keyup.enter="addInfo" placeholder="内容"
                    style="width: 200px;margin-right: 5px;margin-bottom:5px" />
                  <el-button @click="addInfo" test style="margin-bottom:5px">✔️</el-button>
                </span>
              </span>
            </div>
          </div>

          <el-button v-if="!isEdit" text @click="isEdit = true">编辑</el-button>
          <el-button v-if="isEdit" type="primary" @click="update">保存</el-button>
          <el-button v-if="isEdit" @click="initPeopleForm">退出</el-button>
        </el-tab-pane>

        <!-- 添加组员标签页 -->
        <el-tab-pane label="添加组员" name="group" v-if="selectedPeople.id < 0">
          <el-form @submit.prevent :model="newPeopleForm" label-width="70px">
            <el-form-item label="添加到"> {{ selectedPeople.label }} </el-form-item>
            <el-form-item label="姓名">
              <el-input v-model="newPeopleForm.rName" />
            </el-form-item>
            <el-form-item label="电话">
              <el-input v-model="newPeopleForm.rNumber" />
            </el-form-item>
            <el-form-item label="线条标签">
              <el-input v-model="newPeopleForm.rEdgeLabel" />
            </el-form-item>
            <el-form-item label="解释" v-show="newPeopleForm.rName" style="color:#999">
              <span> 我的 {{ selectedPeople.label }} 是 {{ newPeopleForm.rName }} </span>
              <span v-show="newPeopleForm.rEdgeLabel">，他是我的 {{ newPeopleForm.rEdgeLabel }}</span>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="newPeople">提交</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 其后添加标签页 -->
        <el-tab-pane label="其后添加" name="add" v-if="selectedPeople.id > 0">
          <el-form @submit.prevent :model="newPeopleForm" label-width="70px">
            <el-form-item label="添加到">
              {{ selectedPeople.label }}
            </el-form-item>
            <el-form-item label="姓名">
              <el-input v-model="newPeopleForm.rName" />
            </el-form-item>
            <el-form-item label="电话">
              <el-input v-model="newPeopleForm.rNumber" />
            </el-form-item>
            <el-form-item label="线条标签">
              <el-input v-model="newPeopleForm.rEdgeLabel" />
            </el-form-item>
            <el-form-item label="解释" v-show="newPeopleForm.rName" style="color:#999">
              <span v-show="!newPeopleForm.rEdgeLabel">{{ newPeopleForm.rName }} 和 {{ selectedPeople.label }} 有关</span>
              <span v-show="newPeopleForm.rEdgeLabel">
                {{ selectedPeople.label }} 的 {{ newPeopleForm.rEdgeLabel }} 是 {{ newPeopleForm.rName }}
              </span>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="newPeople">提交</el-button>
            </el-form-item>
            <!-- {{ peopleForm }} -->
          </el-form>
        </el-tab-pane>

      </el-tabs>
    </div>
  </div>
</template>

<style scoped>
.people {
  display: flex;
  padding: 10px;
}

.people>.info {
  text-align: center;
  border-right: 1px solid rgba(100, 100, 100, 0.5);
  padding: 10px;
  min-width: 80px;
}

.people>.handl {
  margin-left: 20px;
  width: 100%;
}

.info-item>.key {
  margin-right: 10px;
}

.other-info .info-item>.key {
  margin-right: 50px;
}


.base-info .info-item {
  line-height: 36px;
  font-size: 18px;
}

.other-info .info-item {
  margin-left: 10px;
  line-height: 30px;
  font-size: 16px;
}
</style>